<template>
  <el-row>
    <el-col :span="8" :offset="16" style="text-align:right;">
      <!-- el-badge可以在按钮上做标记，显示信息数量 -->
      <el-badge :value="2" type="warning" class="my-msg">
        <el-button size="small">消息</el-button>
      </el-badge>
      <!-- el-dropdown实现下拉选项 -->
      <el-dropdown>
        <el-avatar :size="50" :src="$store.state.userInfo.avatar">
        </el-avatar>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item @click.native="logout">注销</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-col>
  </el-row>
</template>
<script>
import {resetRouter} from '@/router'

export default {
  name: "TopHeader",
  created() {
    this.createWebsocket();
  },
  methods: {
    createWebsocket() {
      var clientId = this.$store.state.userInfo.username;
      //连接WebSocket节点
      var websocket = new WebSocket("ws://localhost:8081/zjgdcrm/ws/"+clientId);
      //接收到消息发回调方法
      let that = this;
      websocket.onmessage = function (event) {
        that.$notify({
          title: '消息提示',
          dangerouslyUseHTMLString: true,
          duration: 0,
          message: "<a href='#/task/list'>"+event.data+"</a>"
        })
      }
    },
    logout() {
      this.$axios.post("/api/logout").then((res) => {
        if (res.data.code == 200) {//登录成功
          //1.清除登录用户信息
          this.$store.commit("setToken", '')
          this.$store.commit("setUserInfo", {
            username: "未登录",
            avatar: "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
            permissions: []
          })
          //2.清除动态路由
          resetRouter();
          //3.友好提示
          this.$message.success("注销成功")
          //4.跳转登录页
          this.$router.push("/login")
        } else {//登录失败
          //1.友好提示
          this.$message.error(res.data.msg)
        }
      }).catch((err) => {
        console.log(err);
      })
    }
  }
}
</script>
<style>
.my-msg {
  margin-top: -30px;
  margin-right: 20px;
}
</style>